package com.sloan.community.common.vo;

import lombok.Getter;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Getter
public class PageVo<T> {

    private Long total;

    private List<T> data;

    private Integer current;

    private Integer size;

    private Integer firstPage = 1;

    private Integer lastPage;

    // 当前nums展示几页
    private Integer n;

    // 当前页的的左右几页
    private List<Integer> nums;

    private Boolean hasPrePage;

    private Integer prePage;

    private Boolean hasNextPage;

    private Integer nextPage;

    private Boolean showFirstLastPage;

    public PageVo(Long total, List<T> data, Integer current, Integer size, Integer n, Boolean showFirstLastPage) {
        this.total = total;
        this.data = data;
        this.current = current;
        this.size = size;
        //搞成偶数
        this.n = n % 2 == 0 ? n : n - 1;
        // 数据初始化
        this.current = this.getCurrent();
        this.size = this.getSize();
        this.lastPage = this.getLastPage();
        this.hasPrePage = this.getHasPrePage();
        this.prePage = this.getPrePage();
        this.hasNextPage = this.getHasNextPage();
        this.nextPage = this.getNextPage();
        this.showFirstLastPage = showFirstLastPage;
        this.nums = this.getNums();
    }

    public Integer getCurrent() {
        return current == null ? 1 : current;
    }

    public Integer getSize() {
        return size == null ? 10 : size;
    }

    public Integer getLastPage() {
        long num = total / size;
        return (int) ((total % size) == 0 ? num : (num + 1));
    }

    public Boolean getHasPrePage() {
        return current != 1;
    }

    public Integer getPrePage() {
        return getHasPrePage() ? current - 1 : -1;
    }

    public Boolean getHasNextPage() {
        return current < getLastPage();
    }

    public Integer getNextPage() {
        return getHasNextPage() ? current + 1 : -1;
    }


    public List<Integer> getNums() {
        List<Integer> nums = new ArrayList<>();
        //n=4 current=10; 8,9,10,11,12
        int m = getN() / 2;
        int idx = 0;
        int num = current;
        while (idx < m && num - 1 > getFirstPage()) {
            nums.add(0, num - 1);
            num--;
            idx++;
        }

        // 加入当前页码
        if (!showFirstLastPage || (!this.current.equals(firstPage) && !this.current.equals(lastPage))) {
            nums.add(current);
        }

        idx = 0;
        num = current;
        while (idx < m && num + 1 < getLastPage()) {
            nums.add(num + 1);
            num++;
            idx++;
        }

        return nums;
    }
}
